<template>
  <el-dialog title="服药情况" v-if="visible" v-model="visible"
             :before-close="refreshData"
             :close-on-click-modal="false" draggable width="80%">
    <customer-page ref="customerInfoRef" :customerInfo="customerInfo"/>

    <el-row>
      <div class="mb8" style="width: 100%">
        <el-button icon="folder-add" type="primary" class="ml10"
                   @click="formDialogRef.openDialogAdd(state.queryForm.customerId)"
                   v-auth="'blood_bloodxCustomerDrug_add'">
          新 增
        </el-button>
        <el-button plain :disabled="multiple" icon="Delete" type="primary"
                   v-auth="'blood_bloodxCustomerDrug_del'" @click="handleDelete(selectObjs)">
          删除
        </el-button>

<!--        <el-button plain icon="Warning" type="warning" @click="feedBack">反馈服药情况更新</el-button>-->
      </div>
    </el-row>
    <el-table size="small" :data="state.dataList" v-loading="state.loading" border
              :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
              @selection-change="selectionChangHandle"
              :row-style="rowClass"
              @sort-change="sortChangeHandle">
      <el-table-column type="selection" width="40" align="center"/>
      <el-table-column type="index" label="#" width="45"/>
      <el-table-column prop="drug" label="药品名称" width="220" show-overflow-tooltip/>
      <el-table-column prop="frequency" label="药物用法" show-overflow-tooltip/>
      <el-table-column prop="idea" label="用药方式" show-overflow-tooltip/>
<!--      <el-table-column prop="frequency" label="用药频率" show-overflow-tooltip/>-->
      <el-table-column prop="unit" label="计量单位" show-overflow-tooltip/>
<!--      <el-table-column prop="unitMedicine" label="服药计量" show-overflow-tooltip/>-->
      <el-table-column prop="startTime" label="开始时间" show-overflow- width="130">
        <template #default="scope">
          {{ scope.row.startTime?.substring(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="停药时间" show-overflow-tooltip width="130">
        <template #default="scope">
          {{ scope.row.endTime?.substring(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="反馈状态" show-overflow-tooltip>
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="success">正常</el-tag>
          <el-tag v-if="scope.row.status === 1" type="warning">停用</el-tag>
          <el-tag v-if="scope.row.status === 2" type="warning">更改计量</el-tag>
          <el-tag v-if="scope.row.status === 3" type="warning">新增用药</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip width="150"/>
      <el-table-column prop="updateTime" label="更新时间" show-overflow-tooltip width="150"/>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button icon="edit-pen" text type="primary" v-auth="'blood_bloodxCustomerDrug_edit'"
                     @click="formDialogRef.openDialog(scope.row.id)">编辑
          </el-button>
          <el-button icon="delete" text type="primary" v-auth="'blood_bloodxCustomerDrug_del'"
                     @click="handleDelete([scope.row.id])">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination"/>


    <!--    服药情况操作日志-->
    <div class="drug-log" v-if="DrugLogList.length>0">
      <el-steps direction="vertical" finish-status="process" :active="DrugLogList.length">
        <el-step icon="edit-pen" v-for="(item,index) in DrugLogList" :key="index">
          <template #title>
            <el-row>
              <el-col :span="5">操作时间：{{ item.operateTime }}</el-col>
              <el-col :span="3">操作人：{{ item.operateBy }}</el-col>
              <el-col :span="3">操作类型：
                <span class="color-success" v-if="item.operateState === 0">新增</span>
                <span class="color-primary" v-else-if="item.operateState === 1">编辑</span>
                <span class="color-danger" v-else-if="item.operateState === 2">删除</span>
              </el-col>
            </el-row>
          </template>
          <template #description>
            <el-descriptions
                direction="vertical"
                :column="7"
                border
            >
              <el-descriptions-item label="药品名称">{{ item.drug }}</el-descriptions-item>
              <el-descriptions-item label="药物用法">{{ item.frequency }}</el-descriptions-item>
              <el-descriptions-item label="用药方式">{{ item.idea }}</el-descriptions-item>
<!--              <el-descriptions-item label="用药频率">{{ item.frequency }}</el-descriptions-item>-->
              <el-descriptions-item label="计量单位">{{ item.unit }}</el-descriptions-item>
<!--              <el-descriptions-item label="服药计量">{{ item.unitMedicine }}</el-descriptions-item>-->
              <el-descriptions-item label="开始时间">{{ item.startTime?.substring(0, 10) }}</el-descriptions-item>
              <el-descriptions-item label="停药时间">{{ item.endTime?.substring(0, 10) }}</el-descriptions-item>
            </el-descriptions>
          </template>
        </el-step>
      </el-steps>
    </div>


    <!-- 编辑、新增  -->
    <form-dialog ref="formDialogRef" @refresh="refreshList"/>
  </el-dialog>
</template>

<script setup lang="ts" name="systemBloodxCustomerDrug">
import {BasicTableProps, useTable} from "/@/hooks/table";
import {fetchList, delObjs, getDrugLogList, drugFeedbackSpecial} from "/@/api/blood/bloodxCustomerDrug";
import {useMessage, useMessageBox} from "/@/hooks/message";


// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const CustomerPage = defineAsyncComponent(() => import('../../../components/Customer/index.vue'));

const emit = defineEmits(['refresh']);
// 定义查询字典


// 定义变量内容
const formDialogRef = ref()
const visible = ref(false)
// 搜索变量
// const queryRef = ref()
// const showSearch = ref(true)
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
const DrugLogList = ref([]);

const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: fetchList,
  createdIsNeed: false
})

const customerInfo = ref({});

//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  // downBlobFile,
  tableStyle
} = useTable(state)

// 清空搜索条件
// const resetQuery = () => {
//   // 清空搜索条件
//   queryRef.value?.resetFields()
//   // 清空多选
//   selectObjs.value = []
//   getDataList()
// }

// 导出excel
// const exportExcel = () => {
//   downBlobFile('/blood/bloodxCustomerDrug/export', Object.assign(state.queryForm, {ids: selectObjs}), 'bloodxCustomerDrug.xlsx')
// }

const refreshList = () => {
  getDataList(false)
  getDrugLog();
};

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({id}) => id);
  multiple.value = !objs.length;
};

const rowClass = ({row}: any) => {
  return row.status === 1 || row.status === 2 || row.status === 3
      ? {"background-color": "#fff6e5"} : {}
}

const feedBack = async () => {
  try {
    if (state.queryForm.drugStatus === 1) {
      useMessage().warning('已反馈，请勿重复操作');
      return;
    }
    await drugFeedbackSpecial(Object.assign({
      id: state.queryForm.customerId,
      drugStatus: 1
    }));
    useMessage().success('反馈成功');
    state.queryForm.drugStatus = 1;
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
    getDrugLog();
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};


// 打开变发证页面
const openDialog = async (row: any) => {
  visible.value = true
  state.queryForm = {customerId: row.id, drugStatus: row.drugStatus}
  customerInfo.value = row
  getDataList()
  await getDrugLog()

};

const getDrugLog = async () => {
  await getDrugLogList(state.queryForm.customerId).then((res) => {
    DrugLogList.value = res.data;
  });
};

const refreshData = () => {
  visible.value = false;
  emit('refresh');
};

// 暴露变量
defineExpose({
  openDialog
});
</script>

<style lang="scss" scoped>
.drug-log {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #ebeef5;
  //background-color: #f5f7fa;
  border-radius: 4px;
  //.el-step__title{
  //  font-size: 14px;
  //}
  //.el-step__description{
  //  font-size: 12px;
  //}

  :deep(.el-step__description) {
    //font-size: 14px;
    padding: 10px 0;
  }
}
</style>
